package org.leumasjaffe.math.probability;

import java.util.Random;

import org.eclipse.jdt.annotation.NonNull;

import flanagan.analysis.Stat;


public class PoissonRV extends AbstractRV {
	final int lambda;

	public PoissonRV(int l) {
		super();
		this.lambda = l;
	}

	public PoissonRV(@NonNull Random r, int l) {
		super(r);
		this.lambda = l;
	}

	@Override
	public double getEV() {
		return this.lambda;
	}

	@Override
	public double getVar() {
		return this.lambda;
	}

	@Override
	public double getP(double x) {
		int k = (int) x;
		return Math.pow(this.lambda, k)/(Stat.factorial(k)*Math.exp(this.lambda));
	}

	@Override
	public double calcX(double p) {
		if (!isProb(p)) throw new IllegalArgumentException("Arguement is not a valid probability");
		double u = 0;
		int x = 0;
		int n = 1000;
		double q = this.lambda/(double) n;
		while (u<p) {
			x++;
			u += Stat.binomialCoeff(n,(int) x)*Math.pow(q, x)*Math.pow(1-q, n-x);
		}
		return x;
	}

	@Override
	public double getF(double x) {
		int k = (int) x;
		double result = 0;
		for (int i = 0; i <= k; i++)
			result += Math.pow(this.lambda, i)/Stat.factorial(i);
		return result/Math.exp(this.lambda);
	}

}
